package com.charles.video.common.security.utils;

import com.charles.video.api.model.MemberLogin;
import com.charles.video.common.core.constant.SecurityConstants;
import com.charles.video.common.core.constant.TokenConstants;
import com.charles.video.common.core.context.SecurityContextHolder;
import com.charles.video.common.core.utils.ServletUtils;
import com.charles.video.common.core.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Charles-H
 * 
 * 权限工具类
 */
public class SecurityUtils {
    
    /** 获取成员id */
    public static Integer getMemberId() {
        return SecurityContextHolder.getMemberId();
    }
    
    /** 获取成员工号 */
    public static String getMemberNum() {
        return SecurityContextHolder.getMemberNum();
    }
    
    /** 获取成员权限 */
    public static String getMemberRole() {
        return SecurityContextHolder.getMemberRole();
    }
    
    /** 获取成员标识 */
    public static String getMemberKey() {
        return SecurityContextHolder.getMemberKey();
    }
    
    /** 获取登录的成员信息 */
    public static MemberLogin getMemberLogin() {
        return SecurityContextHolder.get(SecurityConstants.MEMBER_LOGIN, MemberLogin.class);
    }
    
    /** 获取请求token */
    public static String getToken() {
        return getToken(ServletUtils.getRequest());
    }
    
    /** 通过请求获取token */
    public static String getToken(HttpServletRequest request) {
        // 在请求头中获取token标识
        String token = request.getHeader(TokenConstants.TOKEN_AUTHENTICATION);
        return replaceTokenPrefix(token);
    }
    
    /** 裁剪token前缀 */
    public static String replaceTokenPrefix(String token) {
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.TOKEN_PREFIX)) {
            token = token.replaceFirst(TokenConstants.TOKEN_PREFIX, "");
        }
        return token;
    }
}

